<template>
  <el-form
    v-loading="formLoading"
    element-loading-spinner="el-icon-loading"
    ref="economicForm"
    :model="economicForm"
    label-width="0"
    class="bg-white min-h-full"
  >
    <div class="form-title">企业发展经济数据信息</div>
    <table class="self-table-form" id="table">
      <thead>
        <th></th>
        <th v-for="item in economicYearList" :key="item.id" class="m-label text-center">
          {{ item.yearV }}
        </th>
      </thead>
      <tbody>
        <tr v-for="(item, thIndex) in economicThList" :key="item + thIndex">
          <td class="m-label text-center">
            {{ economicThObjName[item] }}
          </td>

          <td
            v-for="(yearItem, yearIndex) in economicYearList"
            :key="yearItem.id"
          >
            <el-form-item
              :prop="item + '.' + yearIndex"
              :rules="formRules.inputNumber"
            >
              <el-input
                type="number"
                :step="thIndex >= 18 ? 1 : 0.01"
                @change="handlePropInput(item, yearIndex, thIndex, $event)"
                :placeholder="economicThObjName[item]"
                v-model="economicForm[item][yearIndex]"
              ></el-input>
            </el-form-item>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="flex justify-between py-10 text-center">
      <el-button
        v-if="isSubmit"
        class="confirm-btn tracking-widest"
        type="primary"
        size="medium"
        @click="submitForm"
      >
        保存 / 下一步
      </el-button>

      <DeclareNextItem ref="next" v-show="false" />
    </div>
  </el-form>
</template>

<script>
import {
  checNumber,
  limitLength,
  limitLengthFocus,
} from "@/utils/formRules.js";
import { uploadFileList } from "@/api/declareForm/eonomic.js";

export default {
  name: "EnterpriseEconomicForm",
  props: {
    sourceList: {
      type: Array,
      default: [],
    },
    isSubmit: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    // 企业发展经济数据信息  表头宽度
    economicThWidth() {
      return (str) => {
        let realWidth = parseInt(str.length);
        if (realWidth > 6) {
          return "w-auto";
        }
        if (realWidth > 4 && realWidth <= 6) {
          return "w-28";
        }
        if (realWidth == 3 || realWidth == 4) {
          return "w-20";
        }
      };
    },
    //  增长率
    growRate() {
      return (list) => {
        let res = 0;
        list.forEach((item) => {
          res += Number(item);
        });
        return res;
      };
    },
  },
  data() {
    return {
      formLoading: false,
      economicThObjName: {
        // econmic1: "营业销售收入",
        // econmic2: "总产值",
        // econmic3: "企业研发费用",
        // econmic4: "技术合同交易额",
        // econmic5: "增加值",
        // econmic6: "主营业务利润",
        // econmic7: "利润总额",
        // econmic8: "净利润",
        // econmic9: "缴税总额",
        // econmic10: "年销售额"
      },
      economicThList: [
        // "econmic1",
        // "econmic2",
        // "econmic3",
        // "econmic4",
        // "econmic5",
        // "econmic6",
        // "econmic7",
        // "econmic8",
        // "econmic9",
        // "econmic10"
      ],
      economicYearList: [
        { id: 0, yearV: "" },
        { id: 1, yearV: "" },
        { id: 2, yearV: "" },
        { id: 3, yearV: "" },
      ],
      econmicTypeList: [],
      economicForm: {
        econmic0: ["0.00", "0.00", "0.00", "0.00"],

        econmic1: ["0.00", "0.00", "0.00", "0.00"],
        econmic2: ["0.00", "0.00", "0.00", "0.00"],
        econmic3: ["0.00", "0.00", "0.00", "0.00"],
        econmic4: ["0.00", "0.00", "0.00", "0.00"],
        econmic5: ["0.00", "0.00", "0.00", "0.00"],
        econmic6: ["0.00", "0.00", "0.00", "0.00"],
        econmic7: ["0.00", "0.00", "0.00", "0.00"],
        econmic8: ["0.00", "0.00", "0.00", "0.00"],
        econmic9: ["0.00", "0.00", "0.00", "0.00"],
        econmic10: ["0.00", "0.00", "0.00", "0.00"],
        econmic11: ["0.00", "0.00", "0.00", "0.00"],
        econmic12: ["0.00", "0.00", "0.00", "0.00"],
        econmic13: ["0.00", "0.00", "0.00", "0.00"],
        econmic14: ["0.00", "0.00", "0.00", "0.00"],
        econmic15: ["0.00", "0.00", "0.00", "0.00"],
        econmic16: ["0.00", "0.00", "0.00", "0.00"],
        econmic17: ["0.00", "0.00", "0.00", "0.00"],
        econmic18: ["0", "0", "0", "0"],
        econmic19: ["0", "0", "0", "0"],
        econmic20: ["0", "0", "0", "0"],
        econmic21: ["0", "0", "0", "0"],
        econmic22: ["0", "0", "0", "0"],
        econmic23: ["0", "0", "0", "0"],
        econmic24: ["0", "0", "0", "0"],
        econmic25: ["0", "0", "0", "0"],
        econmic26: ["0", "0", "0", "0"],
        econmic27: ["0", "0", "0", "0"],
        econmic28: ["0", "0", "0", "0"],
        // econmic29: ["0", "0", "0", "0"],
        relationId: "",
      },
      formRules: {
        inputNumber: [
          {
            validator: limitLengthFocus(
              8,
              "不能超过8个字符, 请删减后重试",
              "table",
              true
            ),
            trigger: "blur",
          },
          // { validator: checNumber, trigger: "blur" },
        ],
      },
      defaultFrontName: "econmic",
    };
  },
  watch: {
    sourceList(v) {
      this.initTableTypeList().then(() => {
        this.initSourceList(v);
      });
    },
  },
  created() {
    this.inintTableYears();
    this.initRelationId();
  },
  methods: {
    //  初始化 字典
    initTableTypeList() {
      let dictName = "declare_encomic_type";
      let that = this;

      return new Promise((resolve) => {
        that.getDicts(dictName).then((res) => {
          if (res.code == 200) {
            that.econmicTypeList = res.data;
            that.economicThList = []
            that.econmicTypeList.forEach((item, index) => {
              that.addFormItem(item, index);
            });
            resolve();
          }
        });
      });
    },
    addFormItem(addObj, index) {
      let keyName = this.defaultFrontName + index;
      this.economicThList.push(keyName);
      this.economicThObjName[keyName] = addObj.dictLabel;
      // this.economicForm[keyName] = tempArr;
    },
    initSourceList(v) {
      this.formLoading = true;
      let sourceList = JSON.parse(JSON.stringify(v));
      let that = this;
      let tempFormList = JSON.parse(JSON.stringify(this.economicForm));

      sourceList.forEach((item) => {
        let itemIndex = parseInt(item.type);
        let keyName = that.economicThList[itemIndex];
        let yearIndex = item.year - that.economicYearList[0]["yearV"];
        // tempFormList[keyName][yearIndex] = parseInt(item.total);
        tempFormList[keyName][yearIndex] = item.total;
      });
      this.formLoading = false;
      this.economicForm = tempFormList;
    },
    initRelationId() {
      let realationId = this.$route.query.id;
      if (realationId || realationId == 0) {
        this.economicForm.relationId = parseInt(realationId);
      }
    },
    // 初始化 经济数据信息 中 表头年份
    inintTableYears() {
      let nowYear = new Date().getFullYear() - 1;
      for (let i = 0; i < this.economicYearList.length; i++) {
        this.economicYearList[this.economicYearList.length - (i + 1)]["yearV"] =
          nowYear - i;
      }
    },
    toDecimal2(x) {
      var f = parseFloat(x);
      let isNegative = 0;
      if (x < 0) {
        isNegative = 1;
      } else {
        isNegative = 0;
      }
      if (isNaN(f)) {
        return false;
      }
      x = Math.abs(x);

      var f = Math.round(x * 100) / 100;
      var s = f.toString();
      var rs = s.indexOf(".");
      if (rs < 0) {
        rs = s.length;
        s += ".";
      }
      while (s.length < rs + 2 + 1) {
        s += "0";
      }
      return isNegative == 1 ? "-" + s : s;
    },
    /**
     * @function handlePropInput
     * @param     item [number]: 数组 唯一key id
     * @param     index [nubmer]: 数组 索引
     * @param     thIndex [number]: 每一行数组索引
     * @param     value [number]: 输入框的值
     * @description 表单项股东持有股份 输入
     */
    handlePropInput(item, index, thIndex, value) {
      let unit = this.economicThObjName[item];
      let isToDecimal = unit.indexOf("元") !== -1 || unit.indexOf("%") !== -1;
      let inputV = this.economicForm[item][index];
      let resV = inputV;

      if (!value || !Number(value)) {
        this.economicForm[item][index] = thIndex >= 18 ? "0" : "0.00";
      } else {
        if (resV < 0) {
          console.log("-----------------");
        } else {
        }
        if (isToDecimal) {
          resV = this.toDecimal2(inputV);
        } else {
          resV = parseInt(resV);
        }
        if (resV) {
          this.economicForm[item][index] = resV;
        }
      }
      // 刷新视图
      this.$forceUpdate();
    },

    arrangeFormList() {
      let resArr = [];

      this.economicThList.forEach((item, index) => {
        console.log(item);
        let typeListInfo = this.economicForm[item];

        for (let yearIndex = 0; yearIndex < typeListInfo.length; yearIndex++) {
          let tempObj = {};
          const element = typeListInfo[yearIndex];
          tempObj["type"] = index;

          tempObj["year"] = this.economicYearList[yearIndex]["yearV"];
          tempObj["total"] = element;

          resArr.push(tempObj);
        }
      });
      return resArr;
    },

    submitForm() {
      this.formLoading = true;
      let formName = "economicForm";
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let resArr = this.arrangeFormList();
          let requestObj = {
            relationId: parseInt(this.economicForm.relationId),
            list: resArr,
          };

          uploadFileList(requestObj).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "保存成功",
              });
              // 跳转至下一页
              this.$refs.next.nextDeclareItem();
            } else {
              this.$message.error(res.msg);
            }
            this.formLoading = false;
          });
        } else {
          this.formLoading = false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.m-input-number {
  ::v-deep .el-input__inner {
    text-align: left;
  }
}
</style>
